package com.siqi.hr.system.common.utils;

import com.siqi.hr.system.common.chan.BeSql;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class CollectionUtils {
	private static String split = ",";

	public static <T> Integer getElementIndex(Collection<T> c, T e) {
		if (c == null)
			throw new IllegalArgumentException("集合为空");
		int size = c.size();
		Iterator<T> iterator = c.iterator();
		for (int i = 0; i < size; i++) {
			Object next = iterator.next();
			if (next.equals(e))
				return Integer.valueOf(i);
		}
		return null;
	}

	public static <T> T getIndexElement(Collection<T> c, int index) {
		if (c == null)
			throw new IllegalArgumentException("集合为空");
		int size = c.size();
		if (index > size - 1)
			throw new IllegalArgumentException(index + "超过集合的长度");
		Iterator<T> iterator = c.iterator();

		for (int i = 0; i < size; i++) {
			Object next = iterator.next();
			if (i == index)
				return (T) next;
		}
		return null;
	}


	public static StringBuilder join(Collection<?> c, String split) {
		if (c == null)
			return null;
		int size = c.size();
		if (size == 0)
			return null;
		StringBuilder sb = new StringBuilder();
		Iterator<?> iterator = c.iterator();
		for (int i = 0; i < size; i++) {
			Object next = iterator.next();
			String s = next.toString();
			if (next instanceof BeSql) {
				s = ((BeSql) next).toSqlString().toString();
				if (s.indexOf("'null'") != -1) {
					s = s.substring(0, s.indexOf("'null'")) + "null";
				}
			}

			if (i == size - 1)
				sb.append(s);
			else
				sb.append(s).append(split);
		}
		return sb;
	}

	public static StringBuilder join(Collection<?> c) {
		return join(c, split);
	}

	public static <T> List<T> fillPreChar(int length, T c) {
		if (length < 1)
			throw new IllegalArgumentException("长度小于1");
		List<T> source = new ArrayList<T>();
		for (int i = 0; i < length; i++) {
			source.add(c);
		}
		return source;
	}

}
